//
//  CYImageSearch.m
//  CreditAddressBook
//
//  Created by Lee on 15/8/22.
//  Copyright (c) 2015年 Lee. All rights reserved.
//

#import "CYImageSearch.h"
#import "TFHpple.h"
#import "CYHttpTool.h"
#import "MJExtension.h"
#import "LEBaiduImage.h"
#import "LEBaiduImageParam.h"

static NSString *const _baiduimageURL = @"http://image.baidu.com/search/index";

@interface CYImageSearch ()

@end

@implementation CYImageSearch

+ (void)searchImageFromBaiduWithParams:(LEBaiduImageParam *)params success:(void (^)(LEBaiduImage *baiduImage))success failure:(void (^)(NSError *error))failure{
    
    [CYHttpTool getSerializerWithURL:_baiduimageURL params:@{@"tn": @"baiduimage", @"ie": @"utf-8", @"word": params.word, @"pn": params.pn} success:^(id json) {
//        CYLog(@"%@", json);
        TFHpple *hpple = [[TFHpple alloc] initWithHTMLData:json];
        NSArray * elements  = [hpple searchWithXPathQuery:@"/html/script"];
        
        //网页html
//        NSString *wholeHTML = [[NSString alloc] initWithData:hpple.data encoding:NSUTF8StringEncoding];
//        CYLog(@"%@", wholeHTML);
        
        TFHppleElement * element = elements.lastObject;
        NSString *str = element.content;
//        CYLog(@"%@", str);
        
        NSArray *components = [str componentsSeparatedByString:@"app.setData"];
        for (NSString *strData in components) {
            if ([strData hasPrefix:@"('imgData'"] || [strData hasPrefix:@"(\"imgData\""]) {
                str = strData;
                break;
            }
        }
        str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        str = [str substringFromIndex:11];
        str = [str substringToIndex:str.length - 2];
        
        NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
        NSError *err;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
        
        if(err) {
            CYLog(@"json解析失败:%@",err);
            if (failure) {
                failure(err);
            }
        } else {
            LEBaiduImage *baiduImage = [LEBaiduImage objectWithKeyValues:dic];
            NSMutableArray *data = [NSMutableArray arrayWithArray:baiduImage.data];
            [data removeLastObject];
            baiduImage.data = data;
            if (success) {
                success(baiduImage);
            }
        }
        
    } failure:^(NSError *error) {
        CYLog(@"获取百度图片失败：%@", error);
        if (failure) {
            failure(error);
        }
    }];
}
@end
